// 路由配置文件

import Vue from "vue";
import VueRouter from "vue-router";
//使用路由
Vue.use(VueRouter);

// 引入路由所映射的组件
//导入登录页
import Login from "@/views/login.vue";
// 导入个人中心页
import Personal from "@/views/personal/index.vue";
// 个人信息编辑页
import editPersonal from "@/views/personal/editPersonal.vue";
// 新闻首页
import Index from "@/views/index.vue";
// 注册页面
import Register from "@/views/register.vue";
// 文章详情页
import articleDetail from "@/views/articleDetail.vue";
//用户关注列表
import myFollows from "@/views/personal/myFollows.vue";
//用户收藏列表
import myStars from "@/views/personal/myStars.vue";
// 精彩评论页面
import commentList from "@/views/commentList.vue";
// 频道管理页面
import cateManage from "@/views/cateManage.vue";
// 搜索页面
import search from "@/views/search.vue";

const router = new VueRouter({
  //配置路由
  routes: [
    // 默认重定向
    {
      path: "/",
      redirect: {
        name: "index",
      },
    },
    {
      name: "login",
      path: "/login",
      component: Login,
    },
    {
      name: "personal",
      path: "/personal/:id",
      component: Personal,
    },
    {
      name: "editPersonal",
      path: "/editPersonal/:id",
      component: editPersonal,
    },
    {
      name: "index",
      path: "/index",
      component: Index,
    },
    {
      name: "articleDetail",
      path: "/articleDetail/:id",
      component: articleDetail,
    },
    {
      name: "register",
      path: "/register",
      component: Register,
    },
    {
      name: "myFollows",
      path: "/myFollows",
      component: myFollows,
    },
    {
      name: "myStars",
      path: "/myStars",
      component: myStars,
    },
    {
      name: "commentList",
      path: "/commentList/:id",
      component: commentList,
    },
    {
      name: "cateManage",
      path: "/cateManage",
      component: cateManage,
    },
    {
      name: "search",
      path: "/search",
      component: search,
    },
  ],
});

// 添加导航守卫
// to,from是自带的函数；next()函数表示下一步执行的操作
router.beforeEach((to, from, next) => {
  if (to.name == "personal") {
    let token = localStorage.getItem("news");
    if (token) {
      next();
    } else {
      next({ path: "/login" });
    }
  } else {
    next();
  }
});

// 暴露路由
export default router;
